$(function() {
    $(".form-myt-md-personal-message-inputBasic").data("formOptions", {
        bindEvents : function() {
            var $form = $(this);
            
            var clickSelection = function(source, target) {
                var keywords = $(target).val().split(" ");
                $(source).each(function() {
                    var keyword = $(this).val();
                    var checked = $(this).attr("checked");
                    var exists = false;
                    $.each(keywords, function(i, item) {
                        if (keyword == $.trim(item)) {
                            exists = true;
                            return false;
                        }
                    });
                    if (!checked && exists) {
                        keywords.splice(keywords.indexOf(keyword), 1);
                    }
                    if (checked && !exists) {
                        keywords.push(keyword);
                    }
                })
                $(target).val($.trim(keywords.join(" ")));
            }

            $form.on('click', '.form-group-selectionTargetUsers .controls :checkbox', function(e) {
                clickSelection($(this), $form.find("input[name='targetUsers']"));
            });

            $form.on('click', '.form-group-selectionTargetUsers .control-label :checkbox', function(e) {
                var chks = $form.find(".form-group-selectionTargetUsers .controls :checkbox");
                chks.attr("checked", this.checked);
                clickSelection(chks, $form.find("input[name='targetUsers']"));
            });
        }
    });
});